<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-24 16:32:41
 * @LastEditTime: 2024-07-08 16:28:23
 * @FilePath: \project\src\views\acl\user\index.vue
-->
<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="userSearch" class="userForm">
        <el-form-item label="用户名">
          <el-input v-model="userSearch.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="hsearch">查询</el-button>
          <el-button @click="hreset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top:10px">
      <el-button type="primary" @click="hAdd" icon="plus">添加</el-button>
      <el-popconfirm
        width="220"
        confirm-button-text="确认"
        cancel-button-text="取消"
        icon="InfoFilled"
        :title="`确认删除这${selectUser.length}个用户吗?`"
        @confirm="deleteUserList"
        >
        <template #reference>
          <el-button type="danger" :disabled="!(selectUser.length>0)">批量删除</el-button>
        </template>
      </el-popconfirm>
      

      <el-table :data="userData" border @selection-change="hSelectionChange" style="margin: 10px 0">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="id" label="id" width="100" />
        <el-table-column prop="username" label="用户名字" show-overflow-tooltip />
        <el-table-column prop="name" label="用户名称" show-overflow-tooltip />
        <el-table-column prop="roleName" label="用户角色" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip />
        <el-table-column label="操作" width="280">
          <template #="{row}">
            <el-button size="small" @click="hSetRole(row)" icon="user">分配角色</el-button>
            <el-button size="small" @click="hEdit(row)" icon="edit">编辑</el-button>
            <el-popconfirm
              width="220"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="InfoFilled"
              :title="`确认删除${row.username}这个用户吗?`"
              @confirm="hDeleteUser(row.id)"
              >
              <template #reference>
                <el-button type="danger" icon="delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15]"
        background
        layout="prev, pager, next, jumper,->,sizes, total"
        :total="total"
        @size-change="hSizeChange"
        @current-change="getUserList"
      />
    </el-card>

    <!-- 添加修改用户 -->
    <el-drawer v-model="editUser" direction="rtl">
      <template #header>
        <h4>{{userForm.id?'修改用户':'添加用户'}}</h4>
      </template>
      <template #default>
        <el-form ref="userRef" :model="userForm" :rules="userRules">
          <el-form-item label="用户姓名" prop="username" >
            <el-input v-model="userForm.username" placeholder="请输入用户姓名" clearable />
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input v-model="userForm.name" placeholder="请输入用户昵称" clearable />
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input 
              show-password 
              type="password" 
              v-model="userForm.password" 
              placeholder="请输入用户密码"  
              @keyup.enter.native="hSave" 
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="hcancle">取消</el-button>
          <el-button type="primary" @click="hSave">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色 -->
    <el-drawer v-model="editRole" direction="rtl">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form :model="userForm">
          <el-form-item label="用户姓名" prop="username" >
            <el-input disabled v-model="userForm.username" placeholder="请输入用户姓名" clearable />
          </el-form-item>
          <el-form-item label="职位列表" prop="name">
            <el-checkbox
              v-model="checkAllRole"
              :indeterminate="isIndeterminate"
              @change="hCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedRoles"
              @change="hCheckedRolesChange"
            >
              <el-checkbox v-for="item in allRoleList" :key="item.id" :label="item.roleName" :value="item">
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="editRole = false">取消</el-button>
          <el-button type="primary" @click="doAddRole">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reqUserList, reqAddEditUser, reqRoleList, reqAddRole, reqDeleteUser, reqDeleteUserList } from '@/api/acl/user';
import { RoleData, RoleInfo, UserInfo } from '@/api/acl/user/type';
import { ElMessage, FormRules } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';

let currentPage = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
let userData = ref<UserInfo[]>([])
let selectUser = ref<UserInfo[]>([])
let userSearch = reactive<UserInfo>({
  username:'',
})
let editRole = ref<boolean>(false) // 分配角色
let editUser = ref<boolean>(false) // 修改/添加用户
let userRef = ref()// 添加用户form
let userForm = reactive<UserInfo>({
  username:'',
  name:'',
  password:'',
})

let checkAllRole = ref<boolean>(false)
let isIndeterminate = ref<boolean>(true)
let checkedRoles = ref<RoleInfo[]>([])
let allRoleList = ref<RoleInfo[]>([])

// 校验规则 valid
const validUsername = (rule: any, value: any, callback: any)=>{
  if (value.trim().length>=5) {
    callback()
  } else {
    callback(new Error('用户名长度至少五位'))
  }
}
const validName = (rule: any, value: any, callback: any)=>{
  if (value.trim().length>=5) {
    callback()
  } else {
    callback(new Error('用户昵称长度至少五位'))
  }
}
const validPassword = (rule: any, value: any, callback: any)=>{
  if (value.trim().length>=6) {
    callback()
  } else {
    callback(new Error('密码至少六位'))
  }
}
const userRules = reactive<FormRules<typeof userForm>>( {
  username:[{required: true, trigger: 'blur', validator: validUsername}],
  name:[{required: true, trigger: 'blur', validator: validName}],
  password:[{required: true, trigger: 'blur', validator: validPassword}],
})

// 获取用户
const getUserList = async (page = 1)=> {
  currentPage.value = page
  const res = await reqUserList(currentPage.value, pageSize.value, (userSearch.username as string))
  userData.value = res.data.records
  total.value = res.data.total
}
onMounted(()=>{
  getUserList()
})
const hSizeChange = ()=> {
  getUserList()
}
// 查询
const hsearch = async ()=> {
  getUserList()
}
// 重置
const hreset = ()=> {
  userSearch.username = ''
  getUserList()
}

// 修改/新增用户 ----start----------------------------------------------------------
// 新增
const hAdd = ()=> {
  Object.assign(userForm, {
    id: '',
    username:'',
    name:'',
    password:'',
  })
  nextTick(()=>{
    userRef.value.resetFields()
  })
  editUser.value = true
}
// 编辑
const hEdit = (row:UserInfo)=> {
  Object.assign(userForm, row)
  editUser.value = true
}
// 保存
const hSave = async ()=> {
  await userRef.value.validate()
  const res:any = await reqAddEditUser(userForm)
  if(res.code!=200) return ElMessage({type: 'error',message: userForm.id?'更新失败':'添加失败'})
  ElMessage({type: 'success',message: userForm.id?'更新成功':'添加成功'})
  getUserList(userForm.id?currentPage.value:1)
  editUser.value = false
  // 修改 - 浏览器刷新
  if(userForm.id) window.location.reload()
}
// 取消
const hcancle = ()=> {
  editUser.value = false
  Object.assign(userForm, {
    username:'',
    name:'',
    password:'',
  })
}
// 修改/新增用户 ----end----------------------------------------------------------

// 删除用户 - 单个
const hDeleteUser = async (id:number)=> {
  const res = await reqDeleteUser(id)
  if(res.code!=200) return ElMessage({type: 'error',message: '删除用户失败'})
  ElMessage({type: 'success',message: '删除用户成功'})
  getUserList(userData.value.length>0?currentPage.value:currentPage.value-1) // 重发请求
}
// 选中批量删除用户
const hSelectionChange = async (val:UserInfo[])=> {
  selectUser.value = val
}
// 批量删除用户
const deleteUserList = async ()=>{
  let idList = selectUser.value.map(item=> (item.id as number))
  const res = await reqDeleteUserList(idList)
  if(res.code!=200) return ElMessage({type: 'error',message: '批量删除用户失败'})
  ElMessage({type: 'success',message: '批量删除用户成功'})
  getUserList(userData.value.length>0?currentPage.value:currentPage.value-1) // 重发请求
}

// 分配角色 -----------------------------------------------------------------
const hSetRole = async (row:UserInfo)=> {
  Object.assign(userForm, row)
  editRole.value = true
  const res = await reqRoleList((row.id as number))
  if(res.code!=200) return ElMessage({type: 'error',message: '查询角色失败'})
  allRoleList.value = res.data.allRolesList
  checkedRoles.value = res.data.assignRoles
}
const hCheckAllChange = (val: boolean)=> {
  checkedRoles.value = val ? allRoleList.value : []
  isIndeterminate.value = false
}
const hCheckedRolesChange = (val: UserInfo[])=> {
  const checkedCount = val.length
  checkAllRole.value = checkedCount === allRoleList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRoleList.value.length
}
const doAddRole = async ()=> {
  let params:RoleData = {
    roleIdList: checkedRoles.value.map(item=> (item.id as number)),
    userId: (userForm.id as number),
  }
  const res = await reqAddRole(params)
  if(res.code!=200) return ElMessage({type: 'error',message: '修改角色失败'})
  ElMessage({type: 'success',message: '修改角色成功'})
  editRole.value = false
  getUserList(currentPage.value) // 重发请求
}
</script>

<style lang="scss" scoped>
.userForm{
  display: flex;
  justify-content: space-between;
  margin-bottom: -20px;
}
</style>